package cn.edu.lsnu.mbti.service.impl;

import cn.edu.lsnu.mbti.dto.DepartmentDto;
import cn.edu.lsnu.mbti.entity.Department;
import cn.edu.lsnu.mbti.entity.DepartmentCategory;
import cn.edu.lsnu.mbti.entity.Major;
import cn.edu.lsnu.mbti.mapper.DepartmentCategoryMapper;
import cn.edu.lsnu.mbti.service.DepartmentCategoryService;
import cn.edu.lsnu.mbti.service.DepartmentService;
import cn.edu.lsnu.mbti.service.MajorService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author LindaMan
* @description 针对表【department_category】的数据库操作Service实现
* @createDate 2022-11-05 11:55:10
*/
@Service
public class DepartmentCategoryServiceImpl extends ServiceImpl<DepartmentCategoryMapper, DepartmentCategory>
    implements DepartmentCategoryService{

    @Resource
    private DepartmentService departmentService;
    @Resource
    private MajorService majorService;

    /**
     * 根据分类id查询不同的学科集合
     * @param categoryId
     * @return
     */
    @Override
    public List<DepartmentDto> queryDepartmentListByCategoryId(String categoryId) {
        //根据categoryId从第三张表中查询学科（department）id
        LambdaQueryWrapper<DepartmentCategory> dcWrapper = new LambdaQueryWrapper<>();
        dcWrapper.eq(StrUtil.isNotBlank(categoryId),DepartmentCategory::getCategoryId,categoryId);
        dcWrapper.orderByDesc(DepartmentCategory::getCreateTime);
        List<DepartmentCategory> dcList = this.list(dcWrapper);

        //根据departmentId 查询学科集合
        List<Department> departmentList = dcList.stream().map(item -> {
            return departmentService.getById(item.getDepartmentId());
        }).collect(Collectors.toList());

        //为每个学科查询其下拥有的专业
        List<DepartmentDto> departmentDtoList = departmentList.stream().map(item -> {
            LambdaQueryWrapper<Major> majorWrapper = new LambdaQueryWrapper<>();
            majorWrapper.eq(StrUtil.isNotBlank(item.getId()), Major::getDepartmentId, item.getId());
            majorWrapper.orderByDesc(Major::getCreateTime);
            List<Major> majorList = majorService.list(majorWrapper);
            DepartmentDto dto = new DepartmentDto();
            //对象复制
            BeanUtil.copyProperties(item, dto);
            dto.setMajorList(majorList);
            return dto;
        }).collect(Collectors.toList());

        return departmentDtoList;
    }
}




